package com.example.demo.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {
    //建立保存文件路径
    public static String uploadToTempFolder(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String c = System.getProperty("user.dir");
        //  System.out.println("路径"+temppath);
        /*File.separator 分割线*/
        String temppath = c + "\\src\\main\\resources\\static" + File.separator + "imgs";
        File targetFile = new File(temppath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            file.transferTo(new File(temppath + File.separator + fileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(temppath + File.separator + fileName);
        return temppath + File.separator + fileName;
    }

    //文件对象转换
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        /*File.separator 分割线*/
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File("/" + file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }

        toFile.setReadable(true, false);
        toFile.setExecutable(true, false);
        toFile.setWritable(true, false);
        System.out.println(toFile.getPath());
        Runtime.getRuntime().exec(new StringBuilder().append("chmod -R 777").append(toFile.getAbsolutePath()).toString());
        return toFile;
    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }
}
